package com.icss.trans.util;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @ClassName: XmlUtil
 * @Description: xml工具类
 * @author ICSS
 * @date 2015-3-25 下午2:58:01
 *
 */
public class XmlUtil {

    private static final Logger logger = LoggerFactory.getLogger(XmlUtil.class);

    public static Document readConfig(String data) throws Exception {
        Document config = null;
        SAXReader reader = new SAXReader();
        reader.setEncoding("UTF-8");
        stripNonValidXMLChars(data);
        config = reader.read(new ByteArrayInputStream(data.getBytes("UTF-8")));

        return config;
    }

    /**
     * 格式化XML文件
     * 
     * @param xml
     * @return
     * @throws Exception
     */
    public static String formatXml(String xml) throws Exception {
        Document document = readConfig(xml);
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        StringWriter writer = new StringWriter();
        XMLWriter xmlwriter = new XMLWriter(writer, format);
        xmlwriter.write(document);
        String returnValue = writer.toString();
        writer.close();

        return returnValue;
    }

    /**
     * 
     * @Description: 去除xml中的非法定义字符
     * @param str
     * @return
     * @throws
     */
    public static String stripNonValidXMLChars(String str) {
        if (StringUtils.isEmpty(str)) {
            return str;
        }
        return str.replaceAll("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]", "");
    }

}
